// 展示抄经注意事项
var tipsLayer = null;
function showTips() {
	$(".tips-wrapper").show();
	tipsLayer = layer
			.open({
				type : 1,
				title : [
						"抄经提示",
						'background-color:rgba(110, 82, 1, 0.5);text-align:center;font-weight: 500;color:rgba(255,255,255,1);' ],
				closeBtn : 0,
				shadeClose : true,
				skin : 'layer-ext-moon',
				content : $('.tips-wrapper'),
				area : [ '800px', 'auto' ],
				shift : 4,
				scrollbar : false
			});
}

// 是否抄经完毕
var isWriteOver = false;

$(function() {

	// 禁止粘贴复制
	$(
			'.book-content-wrapper .book-main-wrapper .book-main .content-div .write-div-wrapper form')
			.bind("cut copy paste", function(e) {
				e.preventDefault();
				var options = {
					msg : '',
					time : 3000,
					hasClose : true
				};
				options.type = SELF_ALERT_TYPES.warning;
				options.msg = "禁止粘贴复制,如果遇到难以打出的字可以使用（Ctrl+Y）或者使用（Ctrl+Q）自动填充";
				selfAlert(options);
			});

	// 禁止table键盘
	$(
			$('.book-content-wrapper .book-main-wrapper .book-main .content-div  .write-div-wrapper form')[0])
			.bind('keydown', function(e) {
				var key = e.which;
				if (key == 9) {
					e.preventDefault();
					return false;
				}
			});

	// 自动输入
	$(
			".book-content-wrapper .book-main-wrapper .book-main .content-div .write-div-wrapper .items-wrapper .items .item .item-input")
			.bind(
					'keydown',
					function(e) {
						var key = e.which;
						if (e.ctrlKey && (key == 89 || key == 81)) {
							var _this = $(this);
							var lineVal = _this.closest('.form-group').find(
									'.value-store').val();
							if (_this.val().length == 0
									|| _this.hasClass('item-input-success')) {
								var nextChar = lineVal.substring(
										_this.val().length,
										_this.val().length + 1);

								_this.val(_this.val() + nextChar);
								isLineSuccessOver(_this);
							}
						}
					});

	// 监控变化
	$(
			".book-content-wrapper .book-main-wrapper .book-main .content-div .write-div-wrapper .items-wrapper .items .item .item-input")
			.bind(
					'input propertychange',
					function(e) {
						var _this = $(this);
						var lineVal = _this.closest('.form-group').find(
								'.value-store').val();
						var curVal = _this.val();

						if (lineVal.indexOf(curVal) == 0) {
							isLineSuccessOver(_this);
						} else {
							_this.removeClass('item-input-success');
							_this.addClass('item-input-error');
						}
					});
});

// 每行是否正确结束
function isLineSuccessOver(thisInput) {
	var lineVal = thisInput.closest('.form-group').find('.value-store').val();
	var curVal = thisInput.val();

	thisInput.removeClass('item-input-error');
	thisInput.addClass('item-input-success');
	if (curVal.length == lineVal.length) {
		thisInput.attr('disabled', "disabled");
	}

	var curLineId = thisInput.attr("id");
	var isLastLine = thisInput.hasClass("last");
	if (!isLastLine && curVal.length == lineVal.length) {
		$("#lineId_" + (parseInt(curLineId.split('_')[1]) + 1)).show();
		$("#lineId_" + (parseInt(curLineId.split('_')[1]) + 1))[0].focus();
		thisInput.closest('.item').css('border-left-color', '#3c763d');
	}

	if (isLastLine && curVal.length == lineVal.length) {
		isWriteOver = true;
		updateVerificationCode();
		thisInput.closest('.item').css('border-left-color', '#3c763d');
	}
}

$(function() {

	// 监控供佛选择
	$(
			'#dedicateMeritsForm .table-wrapper table tr td .buddhism-wrapper .select .btn')
			.click(
					function(e) {
						var _this = $(this);
						if (!_this.hasClass("cur-active")) {
							_this.closest('.select').find('.btn').removeClass(
									'cur-active');
							_this.addClass('cur-active');
							$(
									'#dedicateMeritsForm .table-wrapper table tr td .buddhism-wrapper .show-img-wrapper img')
									.attr(
											"src",
											$(_this.find('.value-store')[1])
													.val());
							$('#buddhismInput').val(
									_this.find('.value-store').val());
						}
					});

	var saveBookLayer = null;
	// 弟子恭书
	$('#saveWriteBook')
			.click(
					function() {
						// var saveBookLayer = layer.load(1, {
						// shade : [ 0.5, '#fff' ]
						// // 0.1透明度的白色背景
						// });

						var options = {
							msg : '',
							time : 3000,
							hasClose : true
						};
						options.type = SELF_ALERT_TYPES.warning;

						if (!isWriteOver) {
							options.msg = "请先抄写完毕";
							selfAlert(options);
							return;
						}

						var buddhism = $('#buddhismInput').val();
						var writeUserName = $.trim($('#writeUserNameInput')
								.val());
						var gender = $('input[name=gender]:checked').val();
						var age = $('#ageInput').val();
						var telephone = $('#telephoneInput').val();
						var address = $.trim($('#addressInput').val());
						var dedicateMerits = $
								.trim($('#dedicateMeritsTextarea').val());
						var verificationCode = $.trim($(
								'#verificationCodeInput').val());

						if (!writeUserName) {
							options.msg = "请填写抄经人名称";
							selfAlert(options);
							return;
						}
						if (!age) {
							options.msg = "请填写您的年龄";
							selfAlert(options);
							return;
						}
						if (!address) {
							options.msg = "请填写您的地址";
							selfAlert(options);
							return;
						}

						if (!dedicateMerits) {
							options.msg = "请填写回向功德";
							selfAlert(options);
							return;
						}
						if (!verificationCode) {
							options.msg = "请填写验证码";
							selfAlert(options);
							return;
						}

						if (telephone && !telephone.match(/^\d{11}$/)) {
							options.msg = "请正确填写手机号";
							selfAlert(options);
							return;
						}

						var data = {
							buddhism : buddhism,
							writeUserName : writeUserName,
							gender : gender ? gender : 0,
							age : age,
							telephone : telephone,
							address : address,
							dedicateMerits : dedicateMerits,
							verificationCode : verificationCode,
							bookChapterId : bookChapterId
						};

						saveBookLayer = layer.open({
							type : 3,
							scrollbar : false
						})

						$
								.ajax({
									// async : false,
									data : data,
									type : "post",
									url : baseUrl + "/write/save",
									success : function(response) {
										var _options = {
											msg : '',
											time : 3000,
											hasClose : true
										};

										if (response.responseCode == "000") {
											_options.type = SELF_ALERT_TYPES.success;
											_options.msg = "恭书成功,正在跳转...";
											selfAlert(_options);

											window.location
													.replace(baseUrl
															+ "/write/dedicate-merits-list.html");
										} else {
											layer.close(saveBookLayer);

											_options.type = SELF_ALERT_TYPES.danger;
											_options.msg = response.responseMessage;
											selfAlert(_options);

											if (response.responseCode == "010") {
												updateVerificationCode();
											}
										}
									},
									error : function(XMLHttpRequest,
											textStatus, errorThrown) {
										layer.close(saveBookLayer);
										selfAlert({
											type : SELF_ALERT_TYPES.danger,
											msg : XMLHttpRequest.statusText,
											hasClose : true,
											time : 3000
										});
									}
								});

					});

	$('.verification-code-img').click(function() {
		updateVerificationCode();
	});

});

function updateVerificationCode() {
	$('.verification-code-img').attr("src",
			baseUrl + "/validata/img?d=" + new Date());
}